package models

import (
	"errors"
	"fmt"
	"go-admin/global/orm"
	"go-admin/tools"
	"strconv"
)

type VRSign struct {
	ZxSign
	OrderId    string `json:"orderId, omitempty"`
	CustomName string `json:"customName, omitempty"`
	CustomTel  string `json:"customTel, omitempty"`
	CustomAddr string `json:"customAddr, omitempty"`
}

// 获取VRSign
func (e *VRSign) GetSignById(signId string) (VRSign, error) {
	var doc VRSign
	if tools.NullStr(signId) {
		return doc, errors.New("SignId is empty")
	}
	selectSql := "SELECT zs.*, zo.custom_name, zo.custom_tel, zo.custom_addr" +
		" from zx_sign zs" +
		" join zx_order zo on zs.id = zo.sign_id AND zo.sign_id = " + signId

	orm.Eloquent.Raw(selectSql).Scan(&doc)
	return doc, nil
}

// 获取ZxSign带分页
func (e *VRSign) GetSignPage(pageSize int, pageIndex int) ([]VRSign, int, error) {
	var ret []VRSign

	selectSql := "SELECT zs.*" +
		", zo.id as order_id, zo.custom_name, zo.custom_tel, zo.custom_addr"
	where := " from zx_sign zs join zx_order zo on zs.id = zo.sign_id" +
		" where zo.deleted_at IS NULL"
	if e.CustomName != "" {
		where = fmt.Sprintf("%s AND zo.custom_tel like '%%%s%%'", where, e.CustomName)
	}
	if e.CustomTel != "" {
		where = fmt.Sprintf("%s AND zo.custom_tel = %s", where, e.CustomTel)
	}
	if e.CustomAddr != "" {
		where = fmt.Sprintf("%s AND zo.custom_addr like '%%%s%%'", where, e.CustomAddr)
	}
	if e.SignerId == 0 {
		where = fmt.Sprintf(" %s AND (zs.signer_id = %s OR zo.create_by = %s)", where, e.CreateBy, e.CreateBy)
	} else {
		//where = fmt.Sprintf(" %s AND (zs.signer_id = %s OR zo.create_by = %s)", where, e.CreateBy, e.CreateBy)
		where = fmt.Sprintf(" %s AND zs.signer_id = %d", where, e.SignerId)
	}
	if e.SignState != "" {
		where = fmt.Sprintf("%s AND zs.sign_state = '%s'", where, e.SignState)
	}
	var count int
	selectCountSql := "SELECT count(*) " + where
	orm.Eloquent.Raw(selectCountSql).Count(&count)
	pageSql := " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((pageIndex-1)*pageSize)
	selectSql = selectSql + where + pageSql + ";"
	orm.Eloquent.Raw(selectSql).Scan(&ret)
	// 数据权限控制(如果不需要数据权限请将此处去掉)
	//dataPermission := new(DataPermission)
	//dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
	//table, err := dataPermission.GetDataScope(e.TableName(), table)
	//if err != nil {
	//	return nil, 0, err
	//}
	return ret, count, nil
}
